//
//  PaymentManager.swift
//  NongWanCloud
//
//  Created by YueWen on 2018/8/1.
//  Copyright © 2018年 YueWen. All rights reserved.
//

enum QDPayType: String {
    case ALiPay = "03"
    case Weixin = "04"
    case Union = "05"
    case unknown
}


extension QDPayType {

    // 标题
    var title: String {
        switch self {
        case .ALiPay: return "支付宝"
        case .Weixin: return "微信"
        case .Union: return "银联"
        case .unknown: return ""
        }
    }
}




/// 选择支付方式选择模块的拓展
extension QDPayType {
    
    /// 选择标题
    var payTypeTitle : String {
        switch self {
        case .ALiPay,.Weixin,.Union: return "\(title)支付"
        default: return ""
        }
    }
    
    
    /// 选择默认图片的拓展
    var payTypeImage: String {
        switch self {
        case .ALiPay: return "pt_ali"
        case .Weixin: return "pt_weixin"
        case .Union: return "pt_yinlian"
        default: return ""
        }
    }
    
    /// 详情的默认大图
    var payTypeLargeImage: String {
        switch self {
        case .ALiPay,.Weixin,.Union: return "\(payTypeImage)_large"
        default: return ""
        }
    }
}

protocol QDPayResult: class {

    func complete(orderId: String)
    func fail(error: String,orderId: String)
}




typealias QDPaymentManagerDelegate = QDPayResult


/// 支付的管理单例
class QDPaymentManager: NSObject {
    
    /// 单例对象
    static let sharedInstance = QDPaymentManager()
    /// 代理对象
    var delegate: QDPaymentManagerDelegate?
    /// 支付方式
    var type: QDPayType = .ALiPay
    /// 用于银联跳转的控制器
    weak var viewController: UIViewController?
    
    /// 微信
    private let wxManager = QDPaymentWeixinManager.sharedInstance
    /// 支付宝
    private let aliManager = QDPaymentAliManager.sharedInstance
    /// 银联
    private let unionManager = QDPaymentUnionPay.sharedInstance
    
    private override init(){
        super.init()
        wxManager.delegate = self
        aliManager.delegate = self
        unionManager.delegate = self
    }
    

    
    /// 进行支付
    ///
    /// - Parameters:
    ///   - type: 支付类型
    ///   - data: 支付需要的数据
    ///   - orderId: 订单号
    ///   - delegate: 代理对象
    ///   - viewController: 展示数据的控制器
    func pay(type: QDPayType,data: String,orderId: String = "", delegate: QDPaymentManagerDelegate? = nil,viewController: UIViewController?){
        
        self.delegate = delegate
        self.type = type
        
        switch type {
        case .Weixin: wxManager.pay(data: data,orderId: orderId, viewController: viewController)
        case .ALiPay: aliManager.pay(data: data,orderId: orderId, viewController: viewController)
        case .Union: unionManager.pay(data: data,orderId: orderId, viewController: viewController)
        default: break
        }
    }
}


extension QDPaymentManager : QDPayResult {
    
    func complete(orderId: String) {
        delegate?.complete(orderId: orderId)
    }
    
    func fail(error: String, orderId: String) {
        delegate?.fail(error: error, orderId: orderId)
    }
}






/// 微信支付的管理者
class QDPaymentWeixinManager: NSObject {

    @objc(sharedInstance)
    static let sharedInstance = QDPaymentWeixinManager()
    fileprivate var delegate: QDPayResult?
    fileprivate var orderId = ""

    private override init() {
        super.init()
    }
}


/// 支付宝支付的管理者
class QDPaymentAliManager: NSObject {

    /// 接收通知
    private let PaymentAliResultNoticationName = "PaymentAliResultNoticationName"

    static let sharedInstance = QDPaymentAliManager()
    fileprivate var delegate: QDPayResult?
    fileprivate var orderId = ""

    private override init() {
        super.init()
        
        NotificationCenter.default.addObserver(self, selector: #selector(aliNoticationDidReceive(notification:)), name: NSNotification.Name(rawValue: PaymentAliResultNoticationName), object: AlipaySDK.defaultService())
    }

    @objc func aliNoticationDidReceive(notification: Notification){
        resultHandle(result: notification.userInfo)
    }
}


/// 银联支付的管理者
class QDPaymentUnionPay: NSObject {
    
    /// 接收通知
    private let PaymentUnionResultNoticationName = "PaymentUnionResultNoticationName"
    
    static let sharedInstance = QDPaymentUnionPay()
    fileprivate var delegate: QDPayResult?
    fileprivate var orderId = ""
    
    private override init() {
        super.init()
        
        NotificationCenter.default.addObserver(self, selector: #selector(unionNoticationDidReceive(notification:)), name: NSNotification.Name(rawValue: PaymentUnionResultNoticationName), object: UPPaymentControl.default())
    }
    
    
    @objc func unionNoticationDidReceive(notification: Notification){
        resultHandle(result: notification.userInfo)
    }
}


//MARK: 支付
protocol QDSubPayManager {
    
    func pay(data: String,orderId: String,viewController: UIViewController?)
}



//MARK: 微信
extension QDPaymentWeixinManager: QDSubPayManager {

    func pay(data: String,orderId: String,viewController: UIViewController?) {
        
        self.orderId = orderId
        let request = QDPaymentUntility.wxPaying(data)
        //发送支付请求
        WXApi.send(request)
        print("微信支付!\(data)")
    }
}


extension QDPaymentWeixinManager: WXApiDelegate {

    func onResp(_ resp: BaseResp) {

        if resp is PayResp {
            
            let payResp = resp as! PayResp
            switch payResp.errCode {
            case 0: delegate?.complete(orderId: orderId)
            default: delegate?.fail(error: "微信支付失败",orderId: orderId)
            }
        }
    }
}


//MARK: 支付宝
extension QDPaymentAliManager: QDSubPayManager {

    func pay(data: String,orderId: String,viewController: UIViewController?) {
        
        print("支付宝支付! \(data)")
        self.orderId = orderId
        AlipaySDK.defaultService().payOrder(data, fromScheme: "com.sdjictec.qdmetro") { (result) in
            self.resultHandle(result: result)
        }
    }

    /// 处理
    func resultHandle(result:[AnyHashable: Any]?){
  
        guard let resultDict = result, let resCode = resultDict["resultStatus"] as? String else {
            return
        }
        
        if resCode == "9000" { //支付成功
            delegate?.complete(orderId: orderId); return
        }
        delegate?.fail(error: "支付宝支付失败", orderId: orderId)
    }
}


//MARK: 银联
extension QDPaymentUnionPay: QDSubPayManager {
    
    func pay(data: String,orderId: String,viewController: UIViewController?) {
        
        self.orderId = orderId
        //是个字符串
        print("银联支付!\(data)")

        guard let viewController = viewController else {
            return
        }

        UPPaymentControl.default()?.startPay(data, fromScheme: "com.sdjictec.qdmetro", mode: "00", viewController: viewController)
    }
    
    /// 处理
    func resultHandle(result:[AnyHashable: Any]?){
        
        //MARK: 需要重新对
        guard let resultDict = result,let code = resultDict["code"] as? String else {
            return
        }
        
        if code == "success" {
            print("银联支付成功！")
            self.delegate?.complete(orderId: orderId); return
        }

        self.delegate?.fail(error: "银联支付失败", orderId: orderId)
    }
}

